package logic

import (
	"common/biz"
	"core/alg"
	"core/entity"
	"core/remote"
	"core/xyError"
	"game/component/room"
	"sync"
)

type UnionManager struct {
	sync.RWMutex
	unions map[int64]*Union
}

func NewUnionManager() *UnionManager {
	return &UnionManager{
		unions: make(map[int64]*Union),
	}
}

func (u *UnionManager) GetOrAdd(unionId int64) *Union {
	u.Lock()
	defer u.Unlock()
	union, ok := u.unions[unionId]
	if !ok {
		// 没有就创建一个
		union := NewUnion(unionId, u)
		u.unions[unionId] = union
		return union
	}
	return union
}

// CreateDifferentRandomId 生成一个房间编号
func (u *UnionManager) CreateDifferentRandomId() string {
	roomId := alg.GenRandomId(6)
	for _, v := range u.unions {
		_, ok := v.Rooms[roomId]
		if ok {
			return alg.GenRandomId(6)
		}
	}
	return roomId
}

// GetRoomById 根据房间编号获取房间
func (u *UnionManager) GetRoomById(roomId string) *room.Room {
	for _, union := range u.unions {
		r, ok := union.Rooms[roomId]
		if ok {
			return r
		}
	}
	return nil
}

func (u *UnionManager) JoinRoom(session *remote.Session, roomId string, user *entity.User) *xyError.Error {
	for _, union := range u.unions {
		r, ok := union.Rooms[roomId]
		if ok {
			return r.JoinRoom(session, user)
		}
	}
	return biz.RoomNotExist
}
